<?php


namespace plugin\admin\app\logic\card;

use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\card\Card;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class CardLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new Card;
    }

    public static function getInstance()
    {
        return new self();
    }

    public function getConfig()
    {
        $data = $this->model->where('id', '=', 1)->select(['avatars', 'nicknames', 'signs'])->first()->toArray();
        return $data;
    }


    public function save(Request $request): Response
    {
        $nicknames = explode("\n", trim($request->input('nicknames')));
        $avatars = explode("\n", trim($request->input('avatars')));
        $signs = explode("\n", trim($request->input('signs')));

        $nicknames = array_map(function ($item) {
            return trim($item);
        }, $nicknames);

        $avatars = array_map(function ($item) {
            return trim($item);
        }, $avatars);

        $signs = array_map(function ($item) {
            return trim($item);
        }, $signs);

        $data = [
            'nicknames' => json_encode($nicknames, 256),
            'avatars' => json_encode($avatars, 256),
            'signs' => json_encode($signs, 256),
        ];

        try {
            $this->model->where('id', '=', 1)->update($data);
        } catch (\Exception $e) {
            throw new AdminException(4020, '更新失败');
        }

        return $this->json(0, 'ok', $data);
    }


    public function getInfo(){
        $data = $this->getConfig();

        foreach ($data as &$row) {
            $row = json_decode($row, 1);
        }

        return $data;
    }

}